#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
校准数据结构转换脚本
将校准数据结构从 [attenuation][frequency] = loss 转换为 [frequency][attenuation] = loss
"""

import json
import os
from datetime import datetime


def convert_calibration_structure(input_file, output_file=None):
    """
    转换校准数据结构
    
    Args:
        input_file (str): 输入文件路径
        output_file (str): 输出文件路径，如果为None则覆盖原文件
    
    Returns:
        bool: 转换是否成功
    """
    
    print("🔄 开始转换校准数据结构...")
    print(f"📂 输入文件: {input_file}")
    
    # 检查输入文件是否存在
    if not os.path.exists(input_file):
        print(f"❌ 错误: 文件不存在 - {input_file}")
        return False
    
    try:
        # 读取原始数据
        print("📖 正在读取原始数据...")
        with open(input_file, 'r', encoding='utf-8') as f:
            original_data = json.load(f)
        
        # 检查数据结构
        if not isinstance(original_data, dict):
            print("❌ 错误: 数据格式不正确，应该是字典结构")
            return False
        
        print(f"✅ 原始数据读取成功，包含 {len(original_data)} 个衰减设置")
        
        # 转换数据结构
        print("🔄 正在转换数据结构...")
        converted_data = {}
        
        # 统计信息
        total_data_points = 0
        frequency_set = set()
        attenuation_set = set()
        
        # 遍历原始数据：[attenuation][frequency] = loss
        for attenuation_str, frequency_data in original_data.items():
            if not isinstance(frequency_data, dict):
                print(f"⚠️ 警告: 跳过无效的衰减设置数据 - {attenuation_str}")
                continue
            
            attenuation_set.add(attenuation_str)
            
            # 遍历该衰减设置下的所有频率点
            for frequency_str, loss_value in frequency_data.items():
                frequency_set.add(frequency_str)
                total_data_points += 1
                
                # 转换为新结构：[frequency][attenuation] = loss
                if frequency_str not in converted_data:
                    converted_data[frequency_str] = {}
                
                converted_data[frequency_str][attenuation_str] = loss_value
        
        print(f"📊 转换统计:")
        print(f"   总数据点: {total_data_points}")
        print(f"   频率点数: {len(frequency_set)}")
        print(f"   衰减设置数: {len(attenuation_set)}")
        
        # 验证转换结果
        converted_points = sum(len(att_data) for att_data in converted_data.values())
        if converted_points != total_data_points:
            print(f"⚠️ 警告: 转换后数据点数量不匹配 ({converted_points} != {total_data_points})")
        else:
            print("✅ 数据点数量验证通过")
        
        # 确定输出文件名
        if output_file is None:
            # 创建备份文件
            backup_file = input_file.replace('.json', '_backup.json')
            print(f"💾 创建备份文件: {backup_file}")
            
            with open(backup_file, 'w', encoding='utf-8') as f:
                json.dump(original_data, f, indent=2, ensure_ascii=False)
            
            output_file = input_file
        
        # 保存转换后的数据
        print(f"💾 正在保存转换后的数据到: {output_file}")
        
        # 添加转换信息的元数据
        output_data = {
            "metadata": {
                "structure": "frequency_attenuation",
                "description": "数据结构: [frequency][attenuation] = loss",
                "converted_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                "original_structure": "attenuation_frequency",
                "total_frequencies": len(frequency_set),
                "total_attenuations": len(attenuation_set),
                "total_data_points": total_data_points
            },
            "calibration_data": converted_data
        }
        
        with open(output_file, 'w', encoding='utf-8') as f:
            json.dump(output_data, f, indent=2, ensure_ascii=False)
        
        print("🎉 数据结构转换完成!")
        print(f"📄 输出文件: {output_file}")
        
        # 显示转换前后的结构示例
        print("\n📋 结构转换示例:")
        print("转换前 (原始结构):")
        sample_att = list(attenuation_set)[0] if attenuation_set else "0.0"
        sample_freq = list(frequency_set)[0] if frequency_set else "1000.0"
        if sample_att in original_data and sample_freq in original_data[sample_att]:
            sample_value = original_data[sample_att][sample_freq]
            print(f'   [{sample_att}][{sample_freq}] = {sample_value}')
        
        print("转换后 (新结构):")
        if sample_freq in converted_data and sample_att in converted_data[sample_freq]:
            sample_value = converted_data[sample_freq][sample_att]
            print(f'   [{sample_freq}][{sample_att}] = {sample_value}')
        
        return True
        
    except json.JSONDecodeError as e:
        print(f"❌ JSON解析错误: {str(e)}")
        return False
    except Exception as e:
        print(f"❌ 转换过程中发生错误: {str(e)}")
        return False


def validate_converted_data(file_path):
    """
    验证转换后的数据结构是否正确
    
    Args:
        file_path (str): 转换后的文件路径
    
    Returns:
        bool: 验证是否通过
    """
    
    print("\n🔍 验证转换后的数据结构...")
    
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            data = json.load(f)
        
        # 检查是否有metadata和calibration_data
        if 'calibration_data' not in data:
            print("❌ 验证失败: 缺少calibration_data字段")
            return False
        
        calibration_data = data['calibration_data']
        
        # 检查结构是否为 [frequency][attenuation] = loss
        sample_count = 0
        for frequency, att_data in calibration_data.items():
            if not isinstance(att_data, dict):
                print(f"❌ 验证失败: 频率 {frequency} 的数据不是字典格式")
                return False
            
            for attenuation, loss in att_data.items():
                if not isinstance(loss, (int, float)):
                    print(f"❌ 验证失败: 损耗值不是数值类型 - {frequency}[{attenuation}] = {loss}")
                    return False
                
                sample_count += 1
                if sample_count >= 5:  # 只检查前5个样本
                    break
            
            if sample_count >= 5:
                break
        
        print("✅ 数据结构验证通过")
        print(f"📊 验证统计:")
        print(f"   频率点数: {len(calibration_data)}")
        
        if calibration_data:
            first_freq = list(calibration_data.keys())[0]
            att_count = len(calibration_data[first_freq])
            print(f"   衰减设置数: {att_count}")
        
        # 显示元数据
        if 'metadata' in data:
            metadata = data['metadata']
            print(f"📋 元数据信息:")
            for key, value in metadata.items():
                print(f"   {key}: {value}")
        
        return True
        
    except Exception as e:
        print(f"❌ 验证过程中发生错误: {str(e)}")
        return False


def main():
    """主函数"""
    print("=" * 60)
    print("🔧 校准数据结构转换工具")
    print("=" * 60)
    print("功能: 将数据结构从 [attenuation][frequency] 转换为 [frequency][attenuation]")
    print()
    
    # 目标文件
    input_file = "calibration_data_20250825_180643.json"
    
    # 检查文件是否存在
    if not os.path.exists(input_file):
        print(f"❌ 错误: 目标文件不存在 - {input_file}")
        print("请确认文件路径是否正确")
        return
    
    # 执行转换
    success = convert_calibration_structure(input_file)
    
    if success:
        # 验证转换结果
        validate_converted_data(input_file)
        
        print("\n🎯 转换完成总结:")
        print("✅ 数据结构已成功转换")
        print("✅ 原始文件已备份")
        print("✅ 新结构数据已保存")
        print("\n💡 使用说明:")
        print("- 新的数据结构: calibration_data[frequency][attenuation] = loss")
        print("- 可以通过频率直接访问该频率下的所有衰减设置")
        print("- 更适合按频率进行数据分析和查询")
        
    else:
        print("\n❌ 转换失败，请检查错误信息并重试")


if __name__ == "__main__":
    main()